import 'dart:async';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_common_utils/flutter_common_utils.dart';

/// 全局应用生命周期管理器（单例）
class AppLifecycleManager {
  // 单例实例
  static final AppLifecycleManager _instance = AppLifecycleManager._internal();

  factory AppLifecycleManager() => _instance;

  AppLifecycleManager._internal();

  // 当前状态存储
  AppLifecycleState? _currentState;

  // 状态变化流控制器（广播给订阅者）
  final StreamController<AppLifecycleState> _stateController = StreamController<AppLifecycleState>.broadcast();

  /// 获取当前状态
  AppLifecycleState? get currentState => _currentState;

  /// 状态变化流（供外部订阅）
  Stream<AppLifecycleState> get onStateChanged => _stateController.stream;

  /// 初始化监听
  void init() {
    WidgetsBinding.instance.addObserver(_LifecycleObserver(this));
  }

  // 内部处理生命周期变化
  void _handleLifecycleChange(AppLifecycleState state) {
    LogUtils.i("AppLifecycleManager: $state");
    _currentState = state;
    _stateController.add(state); // 通知所有订阅者
  }
}

/// 生命周期观察者（私有类）
class _LifecycleObserver extends WidgetsBindingObserver {
  final AppLifecycleManager _manager;

  _LifecycleObserver(this._manager);

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    _manager._handleLifecycleChange(state);
  }
}
